const log = console.log.bind(console)
const tc = document.getElementById('turtle-container')
const ctx = tc.getContext('2d')
const angleSymbol = Symbol('angle')
const endPointXSymbol = Symbol('endPointX')
const endPointYSymbol = Symbol('endPointY')
const canvasConfig = {
    [angleSymbol]: 0,
    [endPointXSymbol]: 0,
    [endPointYSymbol]: 0
}

const setPenColor = function setPenColor(color) {
    /* 设置颜色 */
    ctx.strokeStyle = color
    ctx.save()
}
const setPenWidth = function setPenWidth(width) {
    /* 设置宽度 */
    ctx.lineWidth = width
}
const forward = function forward(step) {
    /* 前进 */
    var startPointX = canvasConfig[endPointXSymbol]
    var startPointY = canvasConfig[endPointYSymbol]

    var angle = canvasConfig[angleSymbol]
    var endPointX = startPointX + step * Math.cos(angle * Math.PI / 180)
    var endPointY = startPointY + step * Math.sin(angle * Math.PI / 180)

    // 更新上下文
    canvasConfig[endPointXSymbol] = endPointX
    canvasConfig[endPointYSymbol] = endPointY
    ctx.beginPath()
    ctx.moveTo(startPointX, startPointY)
    
    // var length = Math.sqrt(Math.pow(endPointX - startPointX, 2) + Math.pow(endPointY - startPointY, 2))
    ctx.lineTo(endPointX, endPointY)

    ctx.stroke()
    ctx.closePath()

    ctx.moveTo(endPointX, endPointY)

    // log('pen move to', endPointX, endPointY)
}

const right = function right(angle) {
    // 向右转向
    canvasConfig[angleSymbol] = (canvasConfig[angleSymbol] + angle) % 360
}

const jumpTo = function jumpTo(x, y) {
    canvasConfig[endPointXSymbol] = x
    canvasConfig[endPointYSymbol] = y
    ctx.moveTo(x, y)
}

const setAngle = function setAngle(angle) {
    canvasConfig[angleSymbol] = angle
}

const getAngle = function getAngle() {
    return canvasConfig[angleSymbol]
}

const clear = function clear() {
    ctx.clearRect(0, 0, tc.width, tc.height)
}

